'''
This file handles all the request related to fabric operation
'''

import os

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.db import djangoforms

import django
from django import http

from util import respond
from form import FabricTypeForm
from dao import FabricType

def index(request):
  user = users.GetCurrentUser()
  fabrics = db.GqlQuery('SELECT * FROM FabricType ORDER BY addDate DESC')
  return respond(request, user, 'fabric/list', {'fabrics': fabrics})

def edit(request, fabric_id):
  user = users.GetCurrentUser()
  if user is None:
    return http.HttpResponseForbidden('You must be signed in to add or edit a user')

  fabric = None
  if fabric_id:
    fabric = FabricType.get(db.Key.from_path(FabricType.kind(), int(fabric_id)))
    if fabric is None:
      return http.HttpResponseNotFound('No user exists with that key (%r)' %fabric_id)

  form = FabricTypeForm(data=request.POST or None, instance=fabric)

  if not request.POST:
    return respond(request, user, 'fabric/modify', {'form': form, 'fabric': fabric})

  errors = form.errors
  if not errors:
    try:
      fabric = form.save(commit=False)
    except ValueError, err:
      errors['__all__'] = unicode(err)
  if errors:
    return respond(request, user, 'fabricmodify', {'form': form, 'fabric': fabric})

  fabric.put()

  return http.HttpResponseRedirect('/fabric')

def new(request):
    return edit(request, None)

def delete(request, fabric_id):
    if fabric_id:
        fabric = FabricType.get(db.Key.from_path(FabricType.kind(), int(fabric_id)))
        if fabric is None:
            return http.HttpResponseNotFound('No user exists with that key (%r)' %fabric_id)
        else:
            fabric.delete()
    
    return http.HttpResponseRedirect('/fabric')
    